package com.zirenx.sys.service;

import com.zirenx.sys.model.SysLog;
import com.zirenx.sys.model.SysUser;
import com.zirenx.utils.SysUserUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class SysLogService {

    /**
     * 保存异常日志
     * @param request
     * @param e
     */
    public void saveLog(HttpServletRequest request,Class<?> clazz,Exception e){
        saveLog(request,clazz,e.getMessage());
    }

    /**
     * 保存异常日志
     * @param request
     * @param content
     */
    public void saveLog(HttpServletRequest request,Class<?> clazz,String content){
        save(request,"",content,SysLog.TypeEnum.操作日志);
    }

    public void saveLog(Class<?> clazz,Exception e){
        saveLog(null,clazz,e);
    }

    public void saveLog(HttpServletRequest request,String operation,String content){
        save(request,operation,content,SysLog.TypeEnum.操作日志);
    }

    private void save(HttpServletRequest request,String operation,String content,SysLog.TypeEnum typeEnum){
        SysLog bean = new SysLog();
        if (request!=null){
            SysUser user = SysUserUtils.getUser(request);
            if (user!=null){
                bean.setUserId(user.getId());
                bean.setUsername(user.getUsername());
            }
            bean.setIp(request.getRemoteAddr());
        }
        bean.setParams(content);
        bean.setOperation(operation);
        bean.setGmtCreate(new Date());
        bean.setType(typeEnum.getValue());
        bean.save();
    }
}
